﻿using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using DynamicChart.Model;
using DynamicChart.Service;

namespace DynamicChart.Service.Step.Format;

public class SeriesPieStep : IFormatStep
{
    private readonly LoadService _loadService;
    
    public SeriesPieStep(LoadService loadService)
    {
        _loadService = loadService;
    }
    
    public void Process(IDictionary<string, object> param, IDictionary<string, object> data)
    {
        if (!data.TryGetValue("rawData", out var temp) || temp == null)
        {
            data["series"] = null;
            return;
        }
        
        var rawData = temp as IDictionary<string, object>;
        
        // 数据数量超过 1 不能画饼图
        if (rawData.Count != 1)
        {
            return;
        }
        
        var configs = new Dictionary<string, object>();
        // string radius = "['0%', '50%']";
        List<string> radius = ["0%", "50%"];

        if (param.TryGetValue("id", out var id) && id != null)
        {
            configs = _loadService.GetSeriesConfig(int.Parse(id.ToString()!));
            
            if (configs != null && configs.TryGetValue("innerRadius", out object innerRadius) && 
                configs.TryGetValue("outerRadius", out object outerRadius))
            {
                radius = [$@"{innerRadius.ToString()}%", $@"{outerRadius.ToString()}%"];
            }
        }
        
        data["seriesPie"] = new Dictionary<string, object>
        {
            ["type"] = "pie",
            ["radius"] = radius,
            ["data"] = (rawData["data"] as Dictionary<string, object>)!
                .Select(kvp => {
                    string displayName;

                    if (configs != null && 
                        configs.TryGetValue(kvp.Key, out object config))
                    {
                        displayName = JsonSerializer.Deserialize<Dictionary<string, object>>(config.ToString()!)["name"].ToString();
                    }
                    else
                    {
                        displayName = kvp.Key; // fallback
                    }

                    return new Dictionary<string, object>
                    {
                        ["value"] = kvp.Value,
                        ["name"] = displayName,
                        ["lastName"] = kvp.Key
                    };
                })
                .ToList()
        };
        
        return;
    }
}
